<?php

namespace App\Admin\Http\Controllers\Business;

use Flash;
use App\Admin\Eloquent\User;
use App\Admin\Eloquent\Role;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Profit;
use App\Admin\Eloquent\Information;
use App\Admin\Eloquent\Project;
use App\Admin\Eloquent\ProfitRole;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\ProjectAttr;
use App\Admin\Eloquent\ProjectTypeTemplateAttribute;
use App\Admin\Eloquent\ProjectTypeTemplate;
use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\RoleUser;
use App\Admin\Eloquent\ProjectProfit;
use App\Admin\Eloquent\Article;
use App\Eloquent\TradeRecords;
use App\Admin\Http\Controllers\Controller;
use App\Extensions\Pagination\BootstrapThreePresenter;
use \Illuminate\Http\Request;
use Exception;
use DB;
use Log;

class DemandController extends Controller
{
	/**
	 * 查询发标信息
	 * @param  Request $request [description]
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{
    Project::updateProject();
		$query = $request->all();

		$list = Project::paging_query($query);

    if (!empty($query)) {$list->appends($query);}

		$links = (new BootstrapThreePresenter($list))->render();

		$status=Project::getStatus();

		return view('admin.business.demand.index', compact('list', 'links', 'query','status'));
	}
	/**
	 * 选择项目类型
	 */
	public function cate(){
		$types=Project::getTypes();//项目类型
		return view('admin.business.demand.cate',compact('types'));
	}
	/**
	 * 初始化视图数据
	 * @return [type] [description]
	 */
	protected function iniView($type_id){
		$cates=Code::getByTypeId('gift_activity_cate');//红包活动分类
		$type=ProjectTypeTemplate::find($type_id);//项目类型
		$type_attrs=ProjectTypeTemplateAttribute::where('project_type_template_id','=',$type_id)->orderBy('sort','desc')->get();//项目类型属性
		$promise=Project::getPromises();//担保方式
		$profits=Profit::where('state',1)->get();//分润规则
		$agreement=Information::where(array('position'=>'assure_address_code'))->get();//合同模板
		$notices=Information::where(array('position'=>'notice_adress_code','state'=>'1'))->get();//公告模板
		$collateral_types=Code::getByTypeId('collateral_type');//三方机构类型
		//担保机构
		$role=Role::where('slug','GuaranteeAgency')->first();
		$user_ids=RoleUser::where('role_id',$role->id)->lists('user_id')->toArray();
		$collateral_roles =User::whereIn('id',$user_ids)->get();

		view()->share(compact('cates','notices','type_attrs','type','promise','profits','agreement','collateral_roles','collateral_types'));
	}
	/**
	 * 发标
	 * @param int $id 项目类型编号
	 */
	public function create($id){
		$this->iniView($id);
		return view('admin.business.demand.create');
	}
	/**
	 * 复制项目
	 * @param  [type] $id 项目编号
	 */
	public function copy($pid){
		$info=Project::findOrFail($pid);
		$info->financier_uname=User::where('id','=',$info->financier_id)->value('username');
		$this->iniView($info->project_type_template_id);
		//项目类型属性
		$type_attrs=ProjectAttr::where('project_id','=',$info->id)->get();
		$type_attr=array();
		foreach ($type_attrs as $key => $item) {
			$type_attr[$item->attr_id]=$item->content;
		}
		//分润模板的角色比例
		$modes = ProfitRole::where('profit_id','=',$info->profits_cate)->get();
		$collection=collect($modes->toArray());
		$modes->total=$collection->sum('scale');

		return view('admin.business.demand.copy',compact('info','modes','type_attr'));
	}

	/**
	 * 查看投标项目
	 * @param  [type] $id [description]
	 */
	public function show($id){
		$author = $this->currentUser();

		$info=Project::findOrFail($id);
		//项目属性
		$type_attr=ProjectAttr::where('project_id','=',$info->id)->get();
		//分润模板的角色比例
		$modes = ProfitRole::where('profit_id','=',$info->profits_cate)->get();
		$collection=collect($modes->toArray());
		$modes->total=$collection->sum('scale');
		return view('admin.business.demand.show',compact('info','type_attr','modes','author'));
	}

	/**
	 * 删除项目
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function destroy($id){
		$project=Project::find($id);
		//删除项目属性
		$result=ProjectAttr::where('project_id','=',$id)->delete();
		//删除项目
		$result1=$project->delete();
		Flash::success('删除成功');
		return $this->redirectAction('Business\DemandController@index');
	}

	/**
	 * 修改投标项目
	 * @return [type] [description]
	 */
	public function edit($id){
		$info=Project::findOrFail($id);
		$info->financier_uname=User::where('id','=',$info->financier_id)->value('username');
		//项目类型属性
		$type_attrs=ProjectAttr::where('project_id','=',$info->id)->get();
		$type_attr=array();
		foreach ($type_attrs as $key => $item) {
			if($item->cate==1){
				$type_attr[$item->attr_id]=json_decode($item->content);
			}else{
				$type_attr[$item->attr_id]=$item->content;
			}
		}
		//分润模板的角色比例
		$modes = ProfitRole::where('profit_id','=',$info->profits_cate)->get();
		$collection=collect($modes->toArray());
		$modes->total=$collection->sum('scale');

		$this->iniView($info->project_type_template_id);

		return view('admin.business.demand.edit',compact('info','type_attr','modes'));
	}
	/**
	 * 添加投标项目
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function store(Request $request){
		try {
			DB::beginTransaction();
			$data=$request->input();
			//根据分润规则获取还本方式,投资人收益率
			$profit=Profit::where('id','=',$data['profits_cate'])->first();
			$data['rate_search']=ProfitRole::where(['profit_id'=>$profit->id,'stage'=>'profits_stage_two','role'=>'User'])->value('scale');
			$data['repayment']=$profit->mode;
			//判断项目是否暂存
			$data['status']='none';
			if(isset($data['stop'])){$data['status']='stop';}
			$data['sn']=createSn();
			//添加项目
			$project=new Project($data);
			$project->save();
			//项目属性
			$image = $request->file('attr');//上传的文件
			$attr_data=$project->projectAttr($data,$image);
			ProjectAttr::insert($attr_data);

			DB::commit();
			Flash::success('保存成功');
			return $this->redirectAction('Business\DemandController@index');
		} catch (Exception $e) {
			DB::rollback();
			Flash::error('保存失败!'.$e->getMessage());
			return $this->redirectAction('Business\DemandController@create',[$data['project_type_template_id']]);
		}
	}
	/**
	 * 更新投标项目
	 */
	public function update(Request $request,$id){
		$project=Project::findOrFail($id);
		$data=$request->input();
		//判断项目是否暂存
		$data['status']='none';
		if(isset($data['stop'])){$data['status']='stop';}
		//还本方式,更新投资人收益率
		$profit=Profit::where('id','=',$data['profits_cate'])->first();
		$data['rate_search']=ProfitRole::where(['profit_id'=>$profit->id,'stage'=>'profits_stage_two','role'=>'User'])->value('scale');
		$data['repayment']=$profit->mode;
		//红包规则是否自动递增
		if(!isset($data['gift_money_auto'])){$data['gift_money_auto']=0;}
		//红包规则
		$data['gift_money_cate']=$this->getGiftRules($data);
		//项目属性
		$image = $request->file('attr');//上传的文件
		$attr_data=$project->projectAttr($data,$image);
		ProjectAttr::insert($attr_data);

		if(!$project->update($data)){abort(500);}
		Flash::success('修改成功');
		return $this->redirectAction('Business\DemandController@index');
	}
	/**
	 * 返回项目的红包发放规则
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function getGiftRules($data){
		$rules='';
		if(!empty($data['tou'][0])){
			foreach ($data['tou'] as $key=>$value) {
				if(!empty($data['son'][0])){
					$rules[]=array('tou'=>$value,'son'=>$data['son'][$key]);
				}else{
					$rules[]=array('tou'=>$value,'son'=>'');
				}
			}
		}
		return json_encode($rules);
	}
	/**
	 * 撤销项目
	 * @param  [type]  $id     [description]
	 * @return [type]          [description]
	 */
	public function cancel($id){
		$project=Project::find($id);
		try {
			DB::beginTransaction();
			Project::faileProject($id);
			$project->update(['status'=>'down']);//更新项目状态
			//更新项目的流水记录
			TradeRecords::where('project_id',$id)->update(['sttaus'=>2,'end_time'=>date('Y-m-d H:i:s')]);
			DB::commit();
		} catch (Exception $e) {
			DB::rollback();
		}
		return $this->redirectAction('Business\DemandController@index');
	}
	/**
	 * 一级审核
	 * @return [type] [description]
	 */
	public function check1($id,Request $request){
		$data=$request->all();
		$project=Project::find($id);
		if(isset($data['check'])){$project->update(['status'=>'check']);}
		if(isset($data['none'])){$project->update(['status'=>'none']);}
		return $this->redirectAction('Business\DemandController@index');
	}
	/**
	 * 二级审核
	 * @return [type] [description]
	 */
	public function check2($id,Request $request){
		$data=$request->all();
		$project=Project::find($id);
		$user=User::find($project->financier_id);
		try {
			DB::beginTransaction();
			if(isset($data['rush'])){
				//录入sina标
				$result=$project->sina_project();
				if($result['response_code']!='APPLY_SUCCESS'){
	        abort(600,$result['response_message']);
	      }
				//判断是否含有融资人角色
				if(!$user->roles()->where('slug','Loaner')->exists()){
					$user->roles()->attach(Role::where('slug', 'loaner')->first()->id);
				}
				$project->update(['status'=>'rush','published_at'=>date('Y-m-d H:i:s')]);
				//是否发布公告
				if($project->is_notice){
					$article=array();
					$information=Information::find($project->notice_id);
					$article['title']=str_replace('{date}',date('m-d',strtotime($project->notice_time)),$information->title);
					$article['author']=$project->financier_id;
					$article['article_category_id']=5;
					$article['recommended']=1;
					$article['content']=$information->content;
					foreach ($project->toArray() as $key=>$value) {
						if($key=='finance_time_cate'){
							if($value=='m'){$value=$project->finance_time_num.'个月';}
							if($value=='d'){$value=$project->finance_time_num.'天';}
							if($value=='mm'){$value=$project->finance_time_num.'自然月';}
						}
						if(preg_match('/money/',$key) && $key!='finance_rule_money'){
							$value=($value/10000).'万';
						}
						$article['content']=str_replace('{'.$key.'}', $value, $article['content']);
					}
					$article['published_at']=$project->notice_time;
					Article::insert($article);
				}
			}
			if(isset($data['none'])){$project->update(['status'=>'none']);}
			DB::commit();
		} catch (Exception $e) {
			DB::rollback();
			abort(600,$e->getMessage());
		}
		return $this->redirectAction('Business\DemandController@index');
	}

	/**
	 * 分润详细
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function profit($id,Request $request){
		$query = $request->all();
		$query['project_id']=$id;
		$project=Project::findOrFail($id);//项目
		$list=ProjectProfit::page_query($query);
    if (!empty($query)) {$list->appends($query);}
		$links = (new BootstrapThreePresenter($list))->render();
		return view('admin.business.demand.profit', compact('list', 'links', 'query','project'));
	}
	/**
	 * 投资详细
	 */
	public function investment($id,Request $request){
		$query=$request->all();
		$query['projects_id']=$id;
		$project=Project::findOrFail($id);//项目
		$list=ProjectsUser::page_query($query);
    if (!empty($query)) {$list->appends($query);}
		$links = (new BootstrapThreePresenter($list))->render();
		return view('admin.business.demand.investment', compact('list', 'links', 'query','project'));
	}
	/**
	 * 强制下线
	 * @return [type] [description]
	 */
	public function down($id){
		$project=Project::findOrFail($id);
		$project->update(['status'=>'down']);
		return $this->redirectAction('Business\DemandController@index');
	}
	/**
	 * 获取分润模板的角色比例
	 * @param  Request $q [description]
	 * @return [type]     [description]
	 */
	public function getProfitRoles(Request $q){
    $modes = ProfitRole::where('profit_id','=',$q->input('id'))->get();
    $data=array();
    foreach ($modes as $item) {
    	$data[]=array('role'=>$item->role()->name,'scale'=>$item->scale,'stage_name'=>$item->stage()->name,'stage'=>$item->stage);
    }
		return json_encode($data);
	}
	/**
	 * 获取用户信息
	 * @param  Request $q [description]
	 * @return [type]     [description]
	 */
	public function getUserInfo(Request $q){
		$result=0;
		$name=$q->input('name');
		$user=User::orWhere('username',$name)->orWhere('phone_number',$name)->first();
		if(!empty($user)){
			$result=$user->userInfo;
		}
		return json_encode($result);
	}

	public function trades($id)
	{
		$trades = TradeRecords::where('project_id', $id)->paginate(15);

		$links = (new BootstrapThreePresenter($trades))->render();

		return view('admin.business.demand.trades', compact('trades', 'links'));
	}
	/**
	 * 审核交易记录
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function checkTrade($id){
		$records=TradeRecords::find($id);
		$result=$records->queryTrade();
		dd($result);
	}

	/**
	 * 修改项目合同
	 * @return [type] [description]
	 */
	public function editProjectFile(int $id){
		$project = Project::findOrFail($id);
		if($project->status == 'payment' || $project->status == 'finish')
			return view('admin.business.demand.edit_project_file', compact('project'));
		else
			abort(404);
	}
	public function saveProjectFile(Request $request, int $id){
		$project = Project::findOrFail($id);
		if($project->status == 'payment' || $project->status == 'finish'){
			if(!$request->has('content'))
				return abort(600,'必须填写合同内容');

			$projects_file = $request->input('content');
			// dd($projects_file);
			$project->projects_file = $projects_file;
			$project->save();
			Flash::success('修改项目合同成功');
			return $this->redirectAction('Business\DemandController@index');
		}
		else{
			abort(404);
		}
	}
}